

package com.hazelcast.internal.config.override;

import java.util.*;
import java.util.stream.Collectors;

class ConfigNodeStateTracker {
    Map<String, String> unprocessedNodes(ConfigNode node) {
        List<ConfigNode> nodes = new ArrayList<>();

        findAllUnreadNodes(nodes, node);

        return nodes.stream().map(this::process).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    private void findAllUnreadNodes(List<ConfigNode> acc, ConfigNode node) {
        if (node.hasValue() && !node.isRead()) {
            acc.add(node);
        }

        node.getChildren().values().forEach(c -> findAllUnreadNodes(acc, c));
    }

    private Map.Entry<String, String> process(ConfigNode config) {
        List<String> configSegments = new ArrayList<>();
        ConfigNode current = config;
        do {
            configSegments.add(current.getName());
            current = current.getParent().orElse(null);
        } while (current != null);

        Collections.reverse(configSegments);

        return new AbstractMap.SimpleEntry<>(String.join(".", configSegments), config.getValue());
    }
}
